import React from 'react';
import { Tabs, List, SegmentedControl, WhiteSpace, WingBlank, ListView } from 'antd-mobile';
import { connect } from 'dva';
import moment from 'moment';
import _ from 'lodash';
import Container from '../components/Base/Container';
import ReactEcharts from '../components/Base/Echarts';
import MyIcon from '../components/Base/MyIcon';
import styles from './PerformancePage.css';
import FilterControl from '../components/Base/FilterControl';

const TabPane = Tabs.TabPane;
const ListItem = List.Item;


class MyPerformanceStat extends React.Component {

  formatMoney=(money) => {
    return (money / 10000).toFixed(2);
  }

  renderRow = (rowData, a, index) => {
    const { statAchvSelectedIndex } = this.props;
    let hideColStyle = {};
    if (statAchvSelectedIndex === 0) {
      hideColStyle = { display: 'none' };
    }

    let flagStr = '';
    if (index === '0') flagStr = <span style={{ width: 30 }}><MyIcon type="flag" /></span>;
    else if (index === '1') flagStr = <span style={{ width: 30 }}><MyIcon type="flag_yellow" /></span>;
    else if (index === '2') flagStr = <span style={{ width: 30 }}><MyIcon type="flag_blue" /></span>;
    else flagStr = <span style={{ width: 30 }} />;

    return (<ListItem
      onClick={() => {
      }}
    >
      <div className={styles.header}>
        {flagStr}
        <span className={styles.header_item}>{parseInt(index) + 1}</span>
        <span
          className={styles.header_span1}
        >{rowData.salemanName !== '' ? rowData.salemanName : rowData.saleman}</span>
        <span className={styles.header_span1} style={hideColStyle}>{rowData.rate}</span>
        <span className={styles.header_span1}>{this.formatMoney(rowData.total_money)}</span>
      </div>
    </ListItem>);
  };

  renderVipsRow = (rowData, a, index) => {
    const { statAchvVipsSelectedIndex } = this.props;
    let hideVipsColStyle = {};
    if (statAchvVipsSelectedIndex === 0) {
      hideVipsColStyle = { display: 'none' };
    }

    let flagStr = '';
    if (index === '0') flagStr = <span style={{ width: 30 }}><MyIcon type="flag" /></span>;
    else if (index === '1') flagStr = <span style={{ width: 30 }}><MyIcon type="flag_yellow" /></span>;
    else if (index === '2') flagStr = <span style={{ width: 30 }}><MyIcon type="flag_blue" /></span>;
    else flagStr = <span style={{ width: 30 }} />;

    return (<ListItem
      onClick={() => {
      }}
    >
      <div className={styles.header}>
        {flagStr}
        <span className={styles.header_item}>{parseInt(index) + 1}</span>
        <span
          className={styles.header_span1}
        >{rowData.salemanName !== '' ? rowData.salemanName : rowData.saleman}</span>
        <span className={styles.header_span1} style={hideVipsColStyle}>{rowData.rate}</span>
        <span className={styles.header_span1}>{rowData.vipNum}</span>
      </div>
    </ListItem>);
  };

  getOption3 = () => {
    const { statMyAchv } = this.props;
    const ymData = statMyAchv.data.map((c) => {
      return c._id;
    });
    const totalMoneyData = statMyAchv.data.map((c) => {
      return c.total_money;
    });

    const option = {
      title: {
        // text: '会员增长趋势',
      },
      color: ['#6aa7da'],
      tooltip: {
        trigger: 'axis',
        formatter: '{b0} <br/> <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:rgb(101,166,205)"></span>{a0}: {c0}元',
      },
      grid: {
        containLabel: true,
        left: 10,
        right: 10,
        top: 40,
        bottom: 40,
      },
      legend: {
        // data: ['贡献', '客单价'],
      },
      xAxis: [{
        type: 'category',
        axisTick: {
          alignWithLabel: true,
        },
        data: ymData,
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
      }],
      yAxis: [{
        type: 'value',
        min: 0,
        position: 'left',
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
      }],
      series: [
        {
          name: '销售额',
          type: 'line',
          label: {
            normal: {
              show: false,
            },
          },
          lineStyle: {
            normal: {
              color: "#6aa7da",
              width: 1.5,
              //shadowColor: 'rgba(0,0,0,0.4)',
              //shadowBlur: 10,
              //shadowOffsetY: 10,
            },
          },
          areaStyle: {
            normal: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgb(228,240,250)', // 0% 处的颜色
                }, {
                  offset: 1, color: 'rgba(228,240,250,0.1)', // 100% 处的颜色
                }],
                globalCoord: false, // 缺省为 false
              },
            },
          },
          data: totalMoneyData,
        },
      ],

    };

    return option;
  };

  getOption4 = () => {
    // statMyAchvVips   statMyAchv
    const { statMyAchvVips } = this.props;

    const ymData = statMyAchvVips.data.map((c) => {
      return c._id;
    });
    const totalMoneyData = statMyAchvVips.data.map((c) => {
      return c.vipNums;
    });

    const option = {
      title: {
        // text: '会员增长趋势',
      },
      color: ['#6aa7da'],
      tooltip: {
        trigger: 'axis',
        formatter: '{b0} <br/> <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:rgb(101,166,205)"></span>{a0}: {c0}人',
      },
      grid: {
        containLabel: true,
        left: 10,
        right: 10,
        top: 40,
        bottom: 40,
      },
      legend: {
        // data: ['贡献', '客单价'],
      },
      xAxis: [{
        type: 'category',
        axisTick: {
          alignWithLabel: true,
        },
        data: ymData,
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          // margin:0
        },
      }],
      yAxis: [{
        type: 'value',
        min: 0,
        position: 'left',
        // splitLine: {show: false},
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          // margin:0,
        },
      }],
      series: [
        {
          name: '新客数',
          type: 'line',
          label: {
            normal: {
              show: false,
            },
          },
          lineStyle: {
            normal: {
              color: "#6aa7da",
              width: 1.5,
              //shadowColor: 'rgba(0,0,0,0.4)',
              //shadowBlur: 10,
              //shadowOffsetY: 10,
            },
          },
          areaStyle: {
            normal: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgb(228,240,250)', // 0% 处的颜色
                }, {
                  offset: 1, color: 'rgba(228,240,250,0.1)', // 100% 处的颜色
                }],
                globalCoord: false, // 缺省为 false
              },
            },
          },
          data: totalMoneyData,
        },
      ],
    };

    return option;
  };

  filterControlsChange=(v) => {
    const branchNo = v[0] !== '全部' ? v[0] : undefined;
    const startDate = moment(v[1]).startOf('month').format('YYYY-MM-DD');
    const endDate = moment(v[1]).add(1, 'months').startOf('month').format('YYYY-MM-DD');

    this.props.dispatch({ type: 'stat/fetchStatMyAchv', payload: { branchNo, startDate, endDate } });

    this.props.dispatch({ type: 'stat/fetchStatMyAchvVips', payload: { branchNo, startDate, endDate } });

    this.props.dispatch({ type: 'stat/fetchStatAchvRank', payload: { branchNo, startDate, endDate } });

    this.props.dispatch({ type: 'stat/fetchStatAchvVipsRank', payload: { branchNo, startDate, endDate } });
  }

  componentDidMount() {
    let { branchPickerValue } = this.props;
    branchPickerValue = branchPickerValue.length ? branchPickerValue : ['全部'];
    this.filterControlsChange(branchPickerValue);
  }

  render() {
    const statMyAchv = this.props.statMyAchv;
    const statAchvRank = this.props.statAchvRank;
    const statAchvSelectedIndex = this.props.statAchvSelectedIndex;
    const statMyAchvVips = this.props.statMyAchvVips;
    const statAchvVipsRank = this.props.statAchvVipsRank;
    const statAchvVipsSelectedIndex = this.props.statAchvVipsSelectedIndex;
    const currentUser = this.props.currentUser;
    let hideColStyle = {};
    let hideVipsColStyle = {};
    let hideStatAchvRank = {};

    if (!statMyAchv) return null;

    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });

    if (statAchvSelectedIndex === 0) {
      hideColStyle = { display: 'none' };
    }
    if (statAchvVipsSelectedIndex === 0) {
      hideVipsColStyle = { display: 'none' };
    }
    //童心妇幼连锁的导购不允许看业绩排名
    if(currentUser.roles.indexOf("salesman")>=0 && currentUser.shopId==="zbw_010002"){
      hideStatAchvRank = { display: 'none' };
    }


    return (
      <Container title="我的业绩">
        <div>
          <Tabs defaultActiveKey="2" swipeable={false}>
            <TabPane tab="我的业绩" key="2">
              <div>
                <FilterControl filterControlsChange={this.filterControlsChange} dispatch={this.props.dispatch} hidePickerDate={false} />
                <List renderHeader={() => `我的业绩${_.round(statMyAchv.total_money, 2)}万元`}>
                  <ListItem>
                    <ReactEcharts option={this.getOption3()} />
                  </ListItem>
                </List>
                <List renderHeader={() => `我的新客${statMyAchvVips.vipNums}人,完成进度${statMyAchvVips.quatoRate}`}>
                  <ListItem>
                    <ReactEcharts option={this.getOption4()} />
                  </ListItem>
                </List>
              </div>

            </TabPane>

            <TabPane style={hideStatAchvRank} tab="业绩排名" key="1">
              <div>
                <FilterControl filterControlsChange={this.filterControlsChange} dispatch={this.props.dispatch} hidePickerDate={false} />
                <ListView
                  dataSource={dataSource.cloneWithRows(statAchvRank || [])}
                  renderHeader={() => <div className={styles.header}>
                    <span className={styles.header_item} style={{ marginLeft: 20 }}>排名</span>
                    <span className={styles.header_span1}>姓名</span>
                    <span className={styles.header_span1} style={hideColStyle}>完成率（%）</span>
                    <span className={styles.header_span1}>业绩（万元）</span>
                  </div>}
                  renderRow={this.renderRow}
                  pageSize={10}
                  initialListSize={10}
                  // scrollRenderAheadDistance={500}
                  scrollEventThrottle={10}
                  // onEndReached={this.onEndReached}
                  // onEndReachedThreshold={10}
                  useBodyScroll
                />
              </div>
              <WhiteSpace size="lg" />
              <div>
                <div className={styles.panel}>
                  <p style={{ textAlign: 'center' }}>新客排名</p>
                </div>

                <ListView
                  dataSource={dataSource.cloneWithRows(statAchvVipsRank || [])}
                  renderHeader={() => <div className={styles.header}>
                    <span className={styles.header_item} style={{ marginLeft: 20 }}>排名</span>
                    <span className={styles.header_span1}>姓名</span>
                    <span className={styles.header_span1} style={hideVipsColStyle}>完成率（%）</span>
                    <span className={styles.header_span1}>数量（人）</span>
                  </div>}
                  renderRow={this.renderVipsRow}
                  pageSize={10}
                  initialListSize={10}
                  // scrollRenderAheadDistance={500}
                  scrollEventThrottle={10}
                  // onEndReached={this.onEndReached}
                  // onEndReachedThreshold={10}
                  useBodyScroll
                />
              </div>
            </TabPane>
          </Tabs>
        </div>
      </Container>
    );
  }
}

export default connect((state) => {
  return {
    statMyAchv: state.stat.statMyAchv,
    statAchvRank: state.stat.statAchvRank,
    statAchvSelectedIndex: state.stat.statAchvSelectedIndex,

    statMyAchvVips: state.stat.statMyAchvVips,
    statAchvVipsRank: state.stat.statAchvVipsRank,
    statAchvVipsSelectedIndex: state.stat.statAchvVipsSelectedIndex,

    branchPickerValue: state.stat.branchPickerValue,
    currentUser:state.auth.currentUser
  };
},
  (dispatch) => {
    return {
      dispatch,
      /*fetchStatAchvRank(statAchvSelectedIndex) {
        dispatch({ type: 'stat/fetchStatAchvRank', payload: { statAchvSelectedIndex } });
      },*/
      /*saveStatAchvSelectedIndex(statAchvSelectedIndex) {
        dispatch({ type: 'stat/saveStatAchvSelectedIndex', payload: { statAchvSelectedIndex } });
      },*/
    };
  },
)(MyPerformanceStat);
